//index.js
//获取应用实例
import { getIndex, getPlayMoive } from '../../utils/request.js'
import tmp from '../../utils/tmp.js'

// 获得屏幕宽
let { screenWidth } = wx.getSystemInfoSync();
// console.log(screenWidth)
let swiperWidth = screenWidth / 640*360;


Page({
  /**
   * 页面的初始数据
   */
  data: {
    films: [],
    playing: [],
    playingpages: 1,
    playingcount: 10,
    playingTotal: 1,
    canloadMore: true,
    swiperWidth
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  // 即将上映
  commingSoonDetail: function (ev) {
    let id = ev.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../detailMovie/detailMovie?id=${id}&flag=coming`,
    })
    let info = this.data.films[ev.currentTarget.dataset.index]
    // 电影信息储存
    tmp.setMovie(info)
  },
  // 正在热映
  playingDetail: function(ev) {
    let id = ev.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../detailMovie/detailMovie?id=${id}&flag=playing`,
    })
    let info = this.data.playing[ev.currentTarget.dataset.index]
    // 电影信息储存
    tmp.setMovie(info)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getIniData();

  },

  getIniData(){
    // 请求数据轮播
    getIndex().then(
      (result) => {
        this.setData({
          films: result
        })
      })
    // 请求正在热映的电影
    getPlayMoive(this.data.playingpages, this.data.playingcount).then(
      ({ result, total}) => {
        this.setData({
          playing: result,
          playingTotal: total
        })
      }
    )
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      playingpages: 1
    })
    console.log('onPullDownRefresh', this.data.playingpages)
    this.getIniData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('onReachBottom', this.data.canloadMore)
    if (!this.data.canloadMore) {
      return;
    }
    this.setData({
      playingpages: this.data.playingpages+1
    })
  
    // 请求正在热映的电影
    getPlayMoive(this.data.playingpages, this.data.playingcount).then(
      // 设置加载更多得到数据
      ({ result, total }) => {
        let tmp = this.data.playing.concat(result);
        // 判断是否能加载更多
        if (this.data.playingpages >= this.data.playingTotal) {
          this.setData({
            canloadMore: false,
            playing: tmp,
            playingpages: total
          })
        } else {
          this.setData({
            playing: tmp
          })
        }
      })
  },
})